package com.example.Blog.service;

import com.example.Blog.dao.ArticleDao;
import com.example.Blog.model.Article;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {
    final ArticleDao articleDao;

    public ArticleService(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    // 发布文章
    public Article postArticle(Article article) {
        return this.articleDao.save(article);
    }

    public Article findAnArticle(int articleId) {
        return this.articleDao.findByArticleId(articleId);
    }

    public Page<Article> findAllArticlesInSameType(String articleType, int pageIndex, int pageSize) {
        Sort sort = Sort.by(Sort.Direction.ASC, "articleId");
        //分页
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        return this.articleDao.findAllByArticleType(pageable, articleType);
    }

    public Page<Article> findAllByPageIndex(int pageIndex, int pageSize){
        Sort sort = Sort.by(Sort.Direction.ASC, "articleId");
        //分页
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        //分页查询
        return this.articleDao.findAll(pageable);
    }

    public Page<Article> findAllByArticleBelongTo(int pageIndex, int pageSize, int userId){
        Sort sort = Sort.by(Sort.Direction.ASC, "articleId");
        //分页
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        return this.articleDao.findByArticleBelongTo(pageable, userId);
    }

    // 点赞文章
    // TODO: 2023/11/20  对于参数的选择
    void likeOrStarArticle(Article article) {
        this.articleDao.updateByArticleId(article.getArticleLikes(), article.getArticleStars(), article.getArticleId());
    }

    public void deleteArticle(int articleId) {
        this.articleDao.deleteByArticleId(articleId);
    }

    public void editArticle(Article article) {
        this.articleDao.updateByArticleId(article.getArticleContent(), article.getArticleId());
    }

    public List<Article> findAllArticles(){
        return this.articleDao.findAll();
    }
}
